package com.molichuxing.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.molichuxing.entity.JobFailure;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.utils.BigDecimalUtils;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.framework.utils.DingTalkUtil;
import com.molichuxing.framework.utils.PoiExcelUtils;
import com.molichuxing.property.DingTalkTemplateEnum;
import com.molichuxing.property.EmailSubjectEnum;
import com.molichuxing.service.OrderJobService;
import com.molichuxing.services.business.dto.request.modify.OrderExpireModifyBizDto;
import com.molichuxing.services.business.dto.response.OrderExclusivelBizDto;
import com.molichuxing.services.business.dto.response.OrderMemberBizDto;
import com.molichuxing.services.business.dto.response.OrderScheduleReminderBizDto;
import com.molichuxing.services.business.dto.response.OrderSubscribeBizDto;
import com.molichuxing.services.business.dto.response.UserBizDto;
import com.molichuxing.services.business.dto.response.UserOverdueBlacklistBizDto;
import com.molichuxing.services.business.dto.response.VehicleNameBizDto;
import com.molichuxing.services.business.service.OrderBizService;
import com.molichuxing.services.business.service.OrderScheduleBizService;
import com.molichuxing.services.business.service.OrderSubscribeBizService;
import com.molichuxing.services.business.service.SmsBizService;
import com.molichuxing.services.business.service.UserBizService;
import com.molichuxing.services.business.service.VehicleBizService;
import com.molichuxing.services.infrastructure.dto.request.create.BlacklistCreateDto;
import com.molichuxing.services.infrastructure.dto.response.CarDto;
import com.molichuxing.services.infrastructure.dto.response.DealerDetailDto;
import com.molichuxing.services.infrastructure.dto.response.DealerDto;
import com.molichuxing.services.infrastructure.dto.response.OrderSubscribeDto;
import com.molichuxing.services.infrastructure.dto.response.RiskEmailDto;
import com.molichuxing.services.infrastructure.dto.response.StoreDto;
import com.molichuxing.services.infrastructure.dto.response.UserDto;
import com.molichuxing.services.infrastructure.service.BlacklistService;
import com.molichuxing.services.infrastructure.service.CarService;
import com.molichuxing.services.infrastructure.service.DealerDetailService;
import com.molichuxing.services.infrastructure.service.DealerService;
import com.molichuxing.services.infrastructure.service.IovCarService;
import com.molichuxing.services.infrastructure.service.OrderExclusivelService;
import com.molichuxing.services.infrastructure.service.OrderSubscribeService;
import com.molichuxing.services.infrastructure.service.RiskEmailService;
import com.molichuxing.services.infrastructure.service.StoreService;
import com.molichuxing.services.infrastructure.service.UserService;
import com.molichuxing.services.property.BlacklistTypeEnum;
import com.molichuxing.services.property.OrderPaymentMethodEnum;
import com.molichuxing.services.property.OrderSubscribeStatusEnum;
import com.molichuxing.services.property.OrderTypeEnum;
import com.molichuxing.services.property.RiskEmailReceiveTypeEnum;
import com.molichuxing.services.property.RiskEmailTypeEnum;
import com.molichuxing.services.property.SmsTemplateEnum;
import com.molichuxing.utils.ExcelUtil;
import com.molichuxing.utils.ScheduleEmailUtil;

/**
 * 订单任务service
 * 
 * @author zoumingyu
 * @date 2019年11月17日
 *
 */
@Service("orderJobService")
public class OrderJobServiceImpl implements OrderJobService {
	private static final Logger logger = LoggerFactory.getLogger(OrderJobServiceImpl.class);

	/**
	 * 超里程每公里单价
	 */
	public static final Integer MILEAGE_UNIT_PRICE = 2;
	/**
	 * 超里程上限
	 */
	public static final Integer MILEAGE_BEYOND_UPPER = 30;

	@Value("${profiles.active}")
	private String ACTIVE;

	@Value("${profiles.active.explain}")
	private String ACTIVE_EXPLAIN;

	@Value("${email_account}")
	private String EMAIL_ACCOUNT;

	@Value("${email_password}")
	private String EMAIL_PASSWORD;

	@Value("${dingTalk.order.dealer.url}")
	private String dingTalkOrderDealerUrl;

    @Value("${dingTalk.order.url}")
    private String dingTalkOrderUrl;

	@Resource
	private OrderBizService orderBizService;

	@Resource
	private OrderSubscribeService orderSubscribeService;

	@Resource
	private OrderExclusivelService orderExclusivelService;

	@Resource
	private OrderSubscribeBizService orderSubscribeBizService;

	@Resource
	private OrderScheduleBizService orderScheduleBizService;

	@Resource
	private CarService carService;

	@Resource
	private IovCarService iovCarService;

	@Resource
	private UserService userService;

	@Resource
	private UserBizService userBizService;

	@Resource
	private StoreService storeService;

	@Resource
	private VehicleBizService vehicleBizService;

	@Resource
	private SmsBizService smsBizService;

	@Resource
	private DealerDetailService dealerDetailService;

	@Resource
	private ScheduleEmailUtil scheduleEmailUtil;

	@Resource
	private RiskEmailService riskEmailService;

	@Resource
	private DealerService dealerService;

	@Resource
	private BlacklistService blacklistService;

	/**
	 * 修改到期订阅订单、续订订单（每日0点执行）
	 * 
	 * @return
	 */
	@Override
	public boolean orderExpire() {
		List<JobFailure> failures = new ArrayList<>();
		try {
			// 查询所有前一天到期未还车的订阅订单
			LocalDate day = LocalDate.now().minusDays(1L);
			List<OrderSubscribeDto> orderSubscribeDtos = orderSubscribeService
					.getOrderExpire(day);
			if (orderSubscribeDtos == null || orderSubscribeDtos.isEmpty()) {
				logger.info("[modifyOrderExpire]前一天({})无到期未还车订单", day);
				return true;
			}
			// 车辆ids
			List<Integer> carIds = new ArrayList<>(orderSubscribeDtos.size());
			orderSubscribeDtos.forEach(orderSubscribeDto -> {
				if (orderSubscribeDto.getCarId() != null && orderSubscribeDto.getCarId() > 0) {
					carIds.add(orderSubscribeDto.getCarId());
				} else {
					failures.add(
							new JobFailure("modifyOrderExpire", "订单(" + orderSubscribeDto.getOrderCode() + ")无车辆id"));
				}
			});
			// 根据车辆ids查询车辆信息
			Map<Integer, CarDto> carMap = carService.getCarByIds(carIds);
			if (carMap == null || carMap.isEmpty()) {
				failures.add(new JobFailure("carService.getCarByIds", "车辆信息(ids:" + carIds + ")查询异常"));
				return false;
			}
			// 车架号vins
			List<String> vins = carMap.entrySet().stream().map(e -> e.getValue().getVin()).collect(Collectors.toList());
			// 根据车架号查询车辆行驶里程信息
			Map<String, Integer> currentMileageMap = iovCarService.getCurrentMileage(vins);
			if (currentMileageMap == null || currentMileageMap.isEmpty()) {
				failures.add(new JobFailure("iovCarService.getCurrentMileage", "车辆里程信息(vins:" + vins + ")查询异常"));
				return false;
			}
			List<OrderExpireModifyBizDto> modifyBizDtos = new ArrayList<>();
			for (OrderSubscribeDto orderSubscribeDto : orderSubscribeDtos) {
				// 获取车辆id
				Integer carId = orderSubscribeDto.getCarId();
				if (carId == null || carId <= 0) {
					continue;
				}
				// 获取vin
				String vin = carMap.get(carId) == null ? null : carMap.get(carId).getVin();
				if (StringUtils.isBlank(vin)) {
					continue;
				}
				// 获取里程数
				Integer currentMileage = currentMileageMap.get(vin);
				if (currentMileage == null) {
					failures.add(new JobFailure("modifyOrderExpire", "车辆(" + vin + ")未查到里程信息"));
					continue;
				}
				OrderExpireModifyBizDto modifyBizDto = new OrderExpireModifyBizDto();
				modifyBizDto.setOrderCode(orderSubscribeDto.getOrderCode());
				modifyBizDto.setCurrentMileage(currentMileage);
				modifyBizDto.setOperateId(0);
				modifyBizDto.setOperateName("system");
				modifyBizDtos.add(modifyBizDto);
			}
			// 修改订单信息
			List<Long> failureOrderCodes = orderSubscribeBizService.modifyOrderExpire(modifyBizDtos);
			if (failureOrderCodes != null && !failureOrderCodes.isEmpty()) {
				failures.add(new JobFailure("orderSubscribeBizService.modifyOrderExpire",
						"修改订单(" + failureOrderCodes + ")信息部分失败"));
			}
		} catch (Exception e) {
			logger.error("[modifyOrderExpire]修改到期订阅订单、续订订单异常", e);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + "[modifyOrderExpire]修改到期订阅订单、续订订单异常");
		} finally {
			if (!failures.isEmpty()) {
				String errorMsg = "修改到期订阅订单、续订订单失败：" + failures;
				logger.error("[modifyOrderExpire]" + errorMsg);
				DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + errorMsg);
			}
		}
		return true;
	}

	/**
	 * 还款提醒告知(专属订单还款日前3天触发)（每日9点执行）-业务人员
	 * 
	 * @return
	 */
	@Override
	public boolean orderRepayReminderToServicer() {
		boolean result = true;
		// 查询3天后应还款的用户专属订单
		LocalDate payableDate = LocalDate.now().plusDays(3L);
		String date = DateUtil.formatDate(payableDate);
		List<OrderScheduleReminderBizDto> orderScheduleReminderBizDtos = orderScheduleBizService
				.getReminder(payableDate, false, OrderTypeEnum.EXCLUSIVEL);
		if (orderScheduleReminderBizDtos == null || orderScheduleReminderBizDtos.isEmpty()) {
			logger.info("[orderRepayReminder]专属订单3天后({})无待还款订单", date);
			return result;
		}
		// 查询需要发送邮件人员的邮箱信息
		List<String> emails = getEmail(RiskEmailTypeEnum.ORDER_REPAYMENT_REMINDER); // getRiskEmailList(RiskEmailEnum.ONE.getValue());
		if(null == emails){
			logger.error("专属订单还款日前3天预警发送邮件失败 未配置发送邮件人员的邮箱信息");
			return false;
		}
		try {
		    //发送邮件
			result = orderReminder(orderScheduleReminderBizDtos, "专属订单"+date+"未还款订单预警",
					"亲，附件为" + date + "未还款专属订单，请查收。此邮件为系统自动发送，请勿回复。", emails);
			//发送钉钉
			if(result){
                DingTalkUtil.execute(dingTalkOrderUrl, DingTalkTemplateEnum.ORDER_REPAYMENT_DATE_REMINDER.getTemplate().replace("${date}", date));
            }
		} catch (Exception e) {
			logger.error("专属订单还款日前3天预警发送邮件失败:", e);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + "专属订单还款日前3天预警发送邮件失败" + e.getMessage());
			result = false;
		}

		return result;
	}

	/**
	 * 经销商订单 还款提醒告知-业务人员
	 * @return
	 */
	@Override
	public boolean orderDealerRepayReminderToServicer() {
		boolean result = true;
		// 查询3天后应还款的用户商家订单
		LocalDate payableDate = LocalDate.now().plusDays(3L);
		String date = DateUtil.formatDate(payableDate);
		List<OrderScheduleReminderBizDto> orderScheduleReminderBizDtos = orderScheduleBizService
				.getReminder(payableDate, false, OrderTypeEnum.DEALER);
		if (orderScheduleReminderBizDtos == null || orderScheduleReminderBizDtos.isEmpty()) {
			logger.info("[orderRepayReminder]商家订单3天后({})无待还款订单", date);
			return result;
		}
		// 查询需要发送邮件人员的邮箱信息
		List<String> emails = getEmail(RiskEmailTypeEnum.ORDER_DEALER_REPAYMENT_REMINDER); // getRiskEmailList(RiskEmailEnum.ONE.getValue());
		if(null == emails){
			logger.error("商家订单还款日前3天预警发送邮件失败 未配置发送邮件人员的邮箱信息");
			return false;
		}
		try {
			//附件email
			ByteArrayInputStream is = toExcel(orderScheduleReminderBizDtos);
			scheduleEmailUtil.sendMail("商家订单"+date+"未还款订单预警",
					"亲，附件为" + date + "未还款商家订单，请查收。此邮件为系统自动发送，请勿回复。", emails,
					"商家订单"+date+"未还款订单预警.xlsx",is);
			if(result){
                //钉钉
                DingTalkUtil.execute(dingTalkOrderDealerUrl, DingTalkTemplateEnum.PURCHASE_ORDER_REPAYMENT_DATE_REMINDER.getTemplate().replace("${date}", date));
            }
			for (OrderScheduleReminderBizDto orderScheduleReminderBizDto:orderScheduleReminderBizDtos) {
				DealerDetailDto dealerDetailDto = dealerDetailService.getDealerDetailById(orderScheduleReminderBizDto.getDealerId());
				if(null == dealerDetailDto || null == dealerDetailDto.getEmail()){
					logger.error("经销商订单 还款提醒告知-提前三天提醒商家 经销商信息为空 dealerId:"+ orderScheduleReminderBizDto.getDealerId());
					continue;
				}
				String subject = EmailSubjectEnum.PURCHASE_ORDER_REPAYMENT_DATE_REMINDER.getName().replace("${orderCode}", String.valueOf(orderScheduleReminderBizDto.getOrderCode()));
				String content = scheduleEmailUtil.editorPurchaseOrderReminderContent(String.valueOf(orderScheduleReminderBizDto.getOrderCode()),date);
				//无附件email
				scheduleEmailUtil.send(subject,content,dealerDetailDto.getEmail());
			}

		} catch (Exception e) {
			logger.error("商家订单还款日前3天预警发送邮件失败:", e);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + "商家订单还款日前3天预警发送邮件失败" + e.getMessage());
			result = false;
		}

		return result;
	}

	/**
	 * 逾期后1天提醒（每日9点执行）-业务人员
	 * 
	 * @return
	 */
	@Override
	public boolean orderOverdueReminderToServicer() {
		boolean result = true;
		// 查询前一天应还款的用户专属订单
		LocalDate payableDate = LocalDate.now().minusDays(1L);
		List<OrderScheduleReminderBizDto> orderScheduleReminderBizDtos = orderScheduleBizService
				.getReminder(payableDate, false, OrderTypeEnum.EXCLUSIVEL);
		if (orderScheduleReminderBizDtos == null || orderScheduleReminderBizDtos.isEmpty()) {
			logger.info("[orderOverdue]专属订单当天({})无逾期待还款订单", LocalDate.now());
			return result;
		}
		// 查询需要发送邮件人员的邮箱信息
		List<String> emails = getEmail(RiskEmailTypeEnum.ORDER_OVERDUE_PAYMENT); // getRiskEmailList(RiskEmailEnum.ONE.getValue());
		if(null == emails){
			logger.error("专属订单当天逾期待还款订单发送邮件失败 未配置发送邮件人员的邮箱信息");
			return false;
		}
		try {
			result = orderReminder(orderScheduleReminderBizDtos, "逾期未还款订单",
					"亲，附件为逾期未还款专属订单，请查收。此邮件为系统自动发送，请勿回复。", emails);
            //发送钉钉
            if(result){
                DingTalkUtil.execute(dingTalkOrderUrl, DingTalkTemplateEnum.ORDER_REPAYMENT_OVERDUE_REMINDER.getTemplate());
            }

		} catch (Exception e) {
			logger.error("专属订单当天逾期待还款订单发送邮件失败:", e);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + "专属订单当天逾期待还款订单发送邮件失败" + e.getMessage());
			result = false;
		}

		return result;
	}

	/**
	 * 经销商订单 逾期后1天提醒-业务人员
	 * @return
	 */
	@Override
	public boolean orderDealerOverdueReminderToServicer() {
		boolean result = true;
		// 查询前一天应还款的用户商家订单
		LocalDate payableDate = LocalDate.now().minusDays(1L);
		String date = DateUtil.formatDate(payableDate);
		List<OrderScheduleReminderBizDto> orderScheduleReminderBizDtos = orderScheduleBizService
				.getReminder(payableDate, false, OrderTypeEnum.DEALER);
		if (orderScheduleReminderBizDtos == null || orderScheduleReminderBizDtos.isEmpty()) {
			logger.info("[orderOverdue]商家订单当天({})无逾期待还款订单", LocalDate.now());
			return result;
		}
		// 查询需要发送邮件人员的邮箱信息
		List<String> emails = getEmail(RiskEmailTypeEnum.ORDER_DEALER_OVERDUE_PAYMENT); // getRiskEmailList(RiskEmailEnum.ONE.getValue());
		if(null == emails){
			logger.error("商家订单当天逾期待还款订单发送邮件失败 未配置发送邮件人员的邮箱信息");
			return false;
		}
		try {
			//附件email
			ByteArrayInputStream is = toExcel(orderScheduleReminderBizDtos);
			scheduleEmailUtil.sendMail("商家订单逾期未还款报警",
					"亲，附件为逾期未还款商家订单，请查收。此邮件为系统自动发送，请勿回复。", emails,
					"商家订单逾期未还款报警.xlsx",is);
			if(result){
                //钉钉
                DingTalkUtil.execute(dingTalkOrderDealerUrl, DingTalkTemplateEnum.PURCHASE_ORDER_REPAYMENT_OVERDUE_REMINDER.getTemplate());
            }
			for (OrderScheduleReminderBizDto orderScheduleReminderBizDto:orderScheduleReminderBizDtos) {
				DealerDetailDto dealerDetailDto = dealerDetailService.getDealerDetailById(orderScheduleReminderBizDto.getDealerId());
				if(null == dealerDetailDto || null == dealerDetailDto.getEmail()){
					logger.error("经销商订单 还款提醒告知-逾期一天提醒商家 经销商信息为空 dealerId:"+ orderScheduleReminderBizDto.getDealerId());
					continue;
				}
				String subject = EmailSubjectEnum.PURCHASE_ORDER_REPAYMENT_OVERDUE_REMINDER.getName().replace("${orderCode}", String.valueOf(orderScheduleReminderBizDto.getOrderCode()));
				String content = scheduleEmailUtil.editorPurchaseOrderOverdueReminderContent(String.valueOf(orderScheduleReminderBizDto.getOrderCode()),date);
				//无附件email
				scheduleEmailUtil.send(subject,content,dealerDetailDto.getEmail());
			}
		} catch (Exception e) {
			logger.error("商家订单当天逾期待还款订单发送邮件失败:", e);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + "商家订单当天逾期待还款订单发送邮件失败" + e.getMessage());
			result = false;
		}

		return result;
	}


	/**
	 * 所有逾期未还提醒（每周周一9点执行）-业务人员
	 * 
	 * @return
	 */
	@Override
	public boolean orderOverdueAllReminderToServicer() {
		boolean result = true;
		// 查询所有逾期未还的用户专属订单
		List<OrderScheduleReminderBizDto> orderScheduleReminderBizDtos = orderScheduleBizService
				.getReminder(LocalDate.now(), false, OrderTypeEnum.EXCLUSIVEL);
		if (orderScheduleReminderBizDtos == null || orderScheduleReminderBizDtos.isEmpty()) {
			logger.info("[orderOverdueAllReminder]专属订单无逾期待还款订单");
			return result;
		}

		// 查询需要发送邮件人员的邮箱信息
		List<String> emails = getEmail(RiskEmailTypeEnum.ORDER_OVERDUE_PAYMENT); // getRiskEmailList(RiskEmailEnum.ONE.getValue());
		try {
			result = orderReminder(orderScheduleReminderBizDtos, "逾期未还款订单", "亲，附件为逾期未还款专属订单，请查收。此邮件为系统自动发送，请勿回复。",
					emails);
		} catch (Exception e) {
			logger.error("专属订单所有逾期待还款订单发送邮件失败:", e);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + "专属订单所有逾期待还款订单发送邮件失败" + e.getMessage());
			result = false;
		}

		return result;
	}

	private boolean orderReminder(List<OrderScheduleReminderBizDto> reminderBizDtos, String subject, String content,
			List<String> emails) throws IOException {
		// 生成excel数据
		XSSFWorkbook workbook = ExcelUtil.createHSSFWorkbook(ExcelUtil.EXCLUSIVEL_REPAYREMINDER_TITLE);
		XSSFSheet sheet = workbook.getSheetAt(0);
		int num = 0;
		for (OrderScheduleReminderBizDto reminderBizDto : reminderBizDtos) {
			UserBizDto userDto = null;
			CarDto carDto = null;
			StoreDto storeDto = null;
			try {
				// 查询门店信息
				storeDto = storeService.getStoreById(reminderBizDto.getStoreId());
				// 查询车辆信息
				carDto = carService.getCarById(reminderBizDto.getCarId());
				// 查询用户信息
				userDto = userBizService.getUser(reminderBizDto.getUserId());
			} catch (Exception e) {
				logger.error("[orderReminder]查询其他信息异常：", e);
				continue;
			}
			// 创建行
			XSSFRow row = sheet.createRow(++num);
			// 填充数据
			ExcelUtil.setExclusivelRepayReminderCellValue(row, reminderBizDto, userDto, carDto, storeDto);
			// if (blackList) {
			// // 加入黑名单
			// blacklist(userDto, reason);
			// }
		}
		// 发送带附件的邮件
		ByteArrayOutputStream baos = null;
		InputStream is = null;
		try {
			baos = new ByteArrayOutputStream();
			workbook.write(baos);
			baos.flush();
			byte[] bt = baos.toByteArray();
			is = new ByteArrayInputStream(bt, 0, bt.length);
			baos.close();
			scheduleEmailUtil.sendMail(subject, content, emails, subject + ".xlsx", is);
			is.close();

		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					baos = null;
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					is = null;
				}
			}
		}
		return true;
	}

	/**
	 * 待提车订单，提车提醒短信（每日10点执行）-用户
	 * 
	 * @return
	 */
	@Override
	public boolean orderUnDeliveryReminderToUser() {
		// 查询7日前支付但未提车订单
		orderUnDeliveryReminderToUser(7L);
		// 查询15日前支付但未提车订单
		orderUnDeliveryReminderToUser(15L);
		return true;
	}

	private boolean orderUnDeliveryReminderToUser(Long days) {
		try {
			LocalDate payDate = LocalDate.now().minusDays(days);
			// 根据支付时间查询待提车专属订单信息
			List<OrderMemberBizDto> orders = orderBizService.getUnDeliveryByPayDate(payDate);
			if (orders == null || orders.isEmpty()) {
				logger.info("[orderUnDeliveryReminderToUser]{}天前支付订单无待提车订单", days);
				return true;
			}
			// 车型ids
			List<Integer> vehicleIds = new ArrayList<>();
			// 门店ids
			List<Integer> storeIds = new ArrayList<>();
			// 用户ids
			List<Integer> userIds = new ArrayList<>();
			for (OrderMemberBizDto order : orders) {
				storeIds.add(order.getPlaceStoreId());
				vehicleIds.add(order.getVehicleId());
				userIds.add(order.getUserId());
			}
			// 查询门店
			Map<Integer, StoreDto> storeMap = storeService.getStoreMapByIds(storeIds);
			// 查询车型信息
			Map<Integer, VehicleNameBizDto> vehicleMap = vehicleBizService.getCarByModelNameList(vehicleIds);
			// 查询用户
			Map<Integer, UserDto> userMap = userService.getUsers(userIds);

			for (OrderMemberBizDto order : orders) {
				try {
					Thread.sleep(500);
				} catch (Exception e) {
				}
				StoreDto store = storeMap.get(order.getPlaceStoreId());
				if (store == null || StringUtils.isBlank(store.getFullName())) {
					continue;
				}
				VehicleNameBizDto vehicleName = vehicleMap.get(order.getVehicleId());
				if (vehicleName == null || StringUtils.isBlank(vehicleName.getModelName())) {
					continue;
				}
				UserDto user = userMap.get(order.getUserId());
				if (user == null || StringUtils.isBlank(user.getPhone())) {
					continue;
				}
				JSONObject json = new JSONObject();
				// 商品名称
				String product = null;
				if (OrderTypeEnum.EXCLUSIVEL.equals(order.getType())) {
					// 专属——租期（XX期）/用车方案（回购/不回购）/付款方式 （全款/月付）
					OrderExclusivelBizDto orderExclusive = (OrderExclusivelBizDto) order;
					String paymentMethodStr = OrderPaymentMethodEnum.INSTALLMENT.equals(
							orderExclusive.getPaymentMethod()) ? "月付" : orderExclusive.getPaymentMethod().getName();
					product = vehicleName.getSubBrandName() + " " + vehicleName.getSeriesName() + " "
							+ vehicleName.getModelName() + " " + orderExclusive.getTransportTime() + "期/"
							+ (orderExclusive.getIsBuyback() ? "回购/" : "不回购/") + paymentMethodStr;
				} else if (OrderTypeEnum.SUBSCRIBE.equals(order.getType())) {
					// 订阅——用车时长/基础里程，订阅里程
					OrderSubscribeBizDto OrderSubscribe = (OrderSubscribeBizDto) order;
					product = vehicleName.getSubBrandName() + " " + vehicleName.getSeriesName() + " "
							+ vehicleName.getModelName() + " " + OrderSubscribe.getTransportTime() + "个月/"
							+ OrderSubscribe.getBaseMileage() + "公里, " + OrderSubscribe.getPackageMileage() + "公里";
				}
				json.put("product", product);
				// 订单号
				json.put("order", order.getOrderCode());
				// 门店
				json.put("store", store.getFullName());
				try {
					smsBizService.sendMessage(user.getPhone(), SmsTemplateEnum.ORDER_SMS_ONE.getValue(),
							json.toJSONString(), null);
				} catch (Exception e) {
					logger.error("[orderUnDeliveryReminderToUser]订单" + order.getOrderCode() + "提车提醒短信发送异常", e);
				}
			}
		} catch (Exception e) {
			logger.error("[orderUnDeliveryReminderToUser]" + days + "天前支付订单提车提醒异常：", e);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + days + "天前支付订单提车提醒异常," + e.getMessage());
			return false;
		}

		return true;
	}

	/**
	 * 还款提醒告知(每日10点执行)-用户
	 * 
	 * @return
	 */
	@Override
	public boolean orderRepayReminderToUser() {
		// 还款前7天提醒
		orderRepayReminderToUser(7L);
		// 还款前1天提醒
		orderRepayReminderToUser(1L);
		// 还款当天提醒
		orderRepayReminderToUser(0L);

		return true;
	}

	public boolean orderRepayReminderToUser(Long days) {
		try {
			LocalDate payableDate = LocalDate.now().plusDays(days);
			List<OrderScheduleReminderBizDto> orderScheduleReminderBizDtos = orderScheduleBizService
					.getReminder(payableDate, false, OrderTypeEnum.EXCLUSIVEL);
			if (orderScheduleReminderBizDtos == null || orderScheduleReminderBizDtos.isEmpty()) {
				logger.info("[orderRepayReminderToUser]{}天后无待还款订单", days);
				return true;
			}
			// 用户ids
			List<Integer> userIds = new ArrayList<>();
			for (OrderScheduleReminderBizDto orderScheduleReminderBizDto : orderScheduleReminderBizDtos) {
				userIds.add(orderScheduleReminderBizDto.getUserId());
			}
			// 查询用户
			Map<Integer, UserDto> userMap = userService.getUsers(userIds);

			for (OrderScheduleReminderBizDto orderScheduleReminderBizDto : orderScheduleReminderBizDtos) {
				try {
					Thread.sleep(500);
				} catch (Exception e) {
				}
				UserDto user = userMap.get(orderScheduleReminderBizDto.getUserId());
				if (user == null || StringUtils.isBlank(user.getPhone())) {
					continue;
				}

				JSONObject json = new JSONObject();
				// 用户姓名
				json.put("name", user.getRealName());
				// 商品名称
				json.put("goods", orderScheduleReminderBizDto.getGoodsName());
				// 还款日
				json.put("date", DateUtil.formatDate(orderScheduleReminderBizDto.getPayableDate(), "yyyy年MM月dd日"));
				// 期数
				json.put("num", orderScheduleReminderBizDto.getPeriods());
				// 费用
				json.put("amount", BigDecimalUtils.toString(orderScheduleReminderBizDto.getPayable()));
				try {
					smsBizService.sendMessage(user.getPhone(), SmsTemplateEnum.ORDER_SMS_TWO.getValue(),
							json.toJSONString(), null);
				} catch (Exception e) {
					logger.error(
							"[orderRepayReminderToUser]订单" + orderScheduleReminderBizDto.getOrderCode() + "还款前" + days
									+ "天还款提醒短信异常", e);
				}
			}
		} catch (Exception e) {
			logger.error("[orderRepayReminderToUser]还款前" + days + "天还款提醒短信异常：", e);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + "还款前" + days + "天还款提醒短信异常," + e.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * 还款逾期告知(每日10点执行)-用户
	 * 
	 * @return
	 */
	@Override
	public boolean orderOverdueReminderToUser() {
		// 还款逾期1天未还
		orderOverdueReminderToUser(1L);
		// 还款逾期3天未还
		orderOverdueReminderToUser(3L);
		// 还款逾期7天未还
		orderOverdueReminderToUser(7L);
		return true;
	}

	public boolean orderOverdueReminderToUser(Long days) {
		try {
			LocalDate payableDate = LocalDate.now().minusDays(days);
			List<OrderScheduleReminderBizDto> orderScheduleReminderBizDtos = orderScheduleBizService
					.getReminder(payableDate, false, OrderTypeEnum.EXCLUSIVEL);
			if (orderScheduleReminderBizDtos == null || orderScheduleReminderBizDtos.isEmpty()) {
				logger.info("[orderOverdueReminderToUser]{}天前无逾期待还款订单", days);
				return true;
			}
			// 用户ids
			List<Integer> userIds = new ArrayList<>();
			for (OrderScheduleReminderBizDto orderScheduleReminderBizDto : orderScheduleReminderBizDtos) {
				userIds.add(orderScheduleReminderBizDto.getUserId());
			}
			// 查询用户
			Map<Integer, UserDto> userMap = userService.getUsers(userIds);
			for (OrderScheduleReminderBizDto orderScheduleReminderBizDto : orderScheduleReminderBizDtos) {
				try {
					Thread.sleep(500);
				} catch (Exception e) {
				}
				UserDto user = userMap.get(orderScheduleReminderBizDto.getUserId());
				if (user == null || StringUtils.isBlank(user.getPhone())) {
					continue;
				}

				JSONObject json = new JSONObject();
				// 用户姓名
				json.put("name", user.getRealName());
				// 商品名称
				json.put("product", orderScheduleReminderBizDto.getGoodsName());
				// 期数
				json.put("mun", orderScheduleReminderBizDto.getPeriods());
				// 逾期天数
				json.put("day", days);
				// 费用
				json.put("fee", BigDecimalUtils.toString(orderScheduleReminderBizDto.getPayable()));
				try {
					smsBizService.sendMessage(user.getPhone(), SmsTemplateEnum.ORDER_SMS_THREE.getValue(),
							json.toJSONString(), null);
				} catch (Exception e) {
					logger.error("[orderOverdueReminderToUser]订单" + orderScheduleReminderBizDto.getOrderCode() + "还款逾期"
							+ days + "天还款提醒短信异常", e);
				}
			}
		} catch (Exception e) {
			logger.error("[orderOverdueReminderToUser]还款逾期" + days + "天还款提醒短信异常：", e);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + "还款逾期" + days + "天还款提醒短信异常," + e.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * 续订提醒（每天10点）-用户
	 * 
	 * @return
	 */
	@Override
	public boolean orderRenewReminderToUser() {
		// 续订提醒-10天后到期的订单
		orderRenewReminderToUser(10L);
		// 续订提醒-7天后到期的订单
		orderRenewReminderToUser(7L);
		// 续订提醒-4天后到期的订单
		orderRenewReminderToUser(4L);
		return true;
	}

	private boolean orderRenewReminderToUser(Long days) {
		try {
			// 查询不能存在续订订单的订阅订单
			LocalDate leaseExpire = LocalDate.now().plusDays(days);
			List<OrderSubscribeDto> orderSubscribeDtos = orderSubscribeService.getNoneRenewable(leaseExpire,
					OrderSubscribeStatusEnum.TRADE_USE);
			if (orderSubscribeDtos == null || orderSubscribeDtos.isEmpty()) {
				logger.info("[orderRenewReminderToUser]{}天后无到期未续订订阅订单", days);
				return true;
			}
			// 车辆ids
			List<Integer> carIds = new ArrayList<>(orderSubscribeDtos.size());
			// 用户ids
			List<Integer> userIds = new ArrayList<>();
			for (OrderSubscribeDto orderSubscribeDto : orderSubscribeDtos) {
				if (orderSubscribeDto.getCarId() != null && orderSubscribeDto.getCarId() > 0) {
					carIds.add(orderSubscribeDto.getCarId());
					userIds.add(orderSubscribeDto.getUserId());
				}
			}
			if (carIds.isEmpty()) {
				logger.info("[orderRenewReminderToUser]{}天后到期未续订订阅订单无车辆id", days);
				return true;
			}
			// 根据车辆ids查询车辆信息
			Map<Integer, CarDto> carMap = carService.getCarByIds(carIds);
			if (carMap == null || carMap.isEmpty()) {
				logger.error("车辆信息(ids:" + carIds + ")查询异常");
				return false;
			}
			// 车架号vins
			List<String> vins = carMap.entrySet().stream().map(e -> e.getValue().getVin()).collect(Collectors.toList());
			// 根据车架号查询车辆行驶里程信息
			Map<String, Integer> currentMileageMap = iovCarService.getCurrentMileage(vins);
			if (currentMileageMap == null || currentMileageMap.isEmpty()) {
				logger.error("车辆里程信息(vins:" + vins + ")查询异常");
				return false;
			}
			// 查询用户
			Map<Integer, UserDto> userMap = userService.getUsers(userIds);
			for (OrderSubscribeDto orderSubscribeDto : orderSubscribeDtos) {
				try {
					Thread.sleep(500);
				} catch (Exception e) {
				}
				CarDto car = carMap.get(orderSubscribeDto.getCarId());
				if (car == null || StringUtils.isBlank(car.getVin())) {
					continue;
				}
				Integer currentMileage = currentMileageMap.get(car.getVin());
				if (currentMileage == null) {
					continue;
				}
				UserDto user = userMap.get(orderSubscribeDto.getUserId());
				if (user == null || StringUtils.isBlank(user.getPhone())) {
					continue;
				}
				// 计算是否超里程
				if (currentMileage < orderSubscribeDto.getWarningMileage()) {
					// 未超，提醒用户
					JSONObject json = new JSONObject();
					// 订单号
					json.put("order", orderSubscribeDto.getOrderCode());
					// 剩余天数
					json.put("num", days);
					try {
						smsBizService.sendMessage(user.getPhone(), SmsTemplateEnum.ORDER_SMS_THREE.getValue(),
								json.toJSONString(), null);
					} catch (Exception e) {
						logger.error(
								"[orderRenewReminderToUser]订单" + orderSubscribeDto.getOrderCode() + days + "天后续订提醒短信异常",
								e);
					}
				}
			}
		} catch (Exception e) {
			logger.error("[orderRenewReminderToUser]" + days + "天后续订提醒短信异常:", e);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + days + "天后续订提醒短信异常," + e.getMessage());
			return false;
		}

		return true;
	}

	/**
	 * 加购提醒（每天10点）-用户
	 * 
	 * @return
	 */
	@Override
	public boolean orderPurchaseReminderToUser() {
		// 加购提醒-10天后到期的订单
		orderPurchaseReminderToUser(10L);
		// 加购提醒-7天后到期的订单
		orderPurchaseReminderToUser(7L);
		// 加购提醒-4天后到期的订单
		orderPurchaseReminderToUser(4L);
		// 加购提醒-1天后到期的订单
		orderPurchaseReminderToUser(1L);
		return true;
	}

	private boolean orderPurchaseReminderToUser(Long days) {
		try {
			// 查询订阅订单
			LocalDate leaseExpire = LocalDate.now().plusDays(days);
			List<OrderSubscribeDto> orderSubscribeDtos = orderSubscribeService.getOrderExpire(leaseExpire);
			if (orderSubscribeDtos == null || orderSubscribeDtos.isEmpty()) {
				logger.info("[orderPurchaseReminderToUser]{}天后无到期订阅订单", days);
				return true;
			}
			// 车辆ids
			List<Integer> carIds = new ArrayList<>(orderSubscribeDtos.size());
			// 用户ids
			List<Integer> userIds = new ArrayList<>();
			// 车型ids
			List<Integer> vehicleIds = new ArrayList<>();
			for (OrderSubscribeDto orderSubscribeDto : orderSubscribeDtos) {
				if (orderSubscribeDto.getCarId() != null && orderSubscribeDto.getCarId() > 0) {
					carIds.add(orderSubscribeDto.getCarId());
					userIds.add(orderSubscribeDto.getUserId());
					vehicleIds.add(orderSubscribeDto.getVehicleId());
				}
			}
			if (carIds.isEmpty()) {
				logger.info("[orderRenewReminderToUser]{}天后到期订阅订单无车辆id", days);
				return true;
			}
			// 根据车辆ids查询车辆信息
			Map<Integer, CarDto> carMap = carService.getCarByIds(carIds);
			if (carMap == null || carMap.isEmpty()) {
				logger.error("车辆信息(ids:" + carIds + ")查询异常");
				return false;
			}
			// 车架号vins
			List<String> vins = carMap.entrySet().stream().map(e -> e.getValue().getVin()).collect(Collectors.toList());
			// 根据车架号查询车辆行驶里程信息
			Map<String, Integer> currentMileageMap = iovCarService.getCurrentMileage(vins);
			if (currentMileageMap == null || currentMileageMap.isEmpty()) {
				logger.error("车辆里程信息(vins:" + vins + ")查询异常");
				return false;
			}
			// 查询用户
			Map<Integer, UserDto> userMap = userService.getUsers(userIds);
			// 查询车型信息
			Map<Integer, VehicleNameBizDto> vehicleMap = vehicleBizService.getCarByModelNameList(vehicleIds);
			for (OrderSubscribeDto orderSubscribeDto : orderSubscribeDtos) {
				try {
					Thread.sleep(500);
				} catch (Exception e) {
				}
				CarDto car = carMap.get(orderSubscribeDto.getCarId());
				if (car == null || StringUtils.isBlank(car.getVin())) {
					continue;
				}
				Integer currentMileage = currentMileageMap.get(car.getVin());
				if (currentMileage == null) {
					continue;
				}
				UserDto user = userMap.get(orderSubscribeDto.getUserId());
				if (user == null || StringUtils.isBlank(user.getPhone())) {
					continue;
				}
				VehicleNameBizDto vehicleName = vehicleMap.get(orderSubscribeDto.getVehicleId());
				if (vehicleName == null || StringUtils.isBlank(vehicleName.getModelName())) {
					continue;
				}
				// 计算是否超里程
				Integer beyondMileage = currentMileage - orderSubscribeDto.getWarningMileage();
				if (beyondMileage > 0 && beyondMileage < MILEAGE_BEYOND_UPPER) {
					// 提醒用户可加购
					JSONObject json = new JSONObject();
					// 商品名称
					json.put("product",
							vehicleName.getSubBrandName() + " " + vehicleName.getSeriesName() + " "
									+ vehicleName.getModelName() + " " + orderSubscribeDto.getTransportTime() + "个月/"
									+ orderSubscribeDto.getBaseMileage() + "公里, "
									+ orderSubscribeDto.getPackageMileage() + "公里");
					// 超里程数
					json.put("mileage", beyondMileage);
					// 超出费用
					json.put("fee", MILEAGE_UNIT_PRICE);
					// 超里程数上限
					json.put("mileage1", MILEAGE_BEYOND_UPPER);
					try {
						smsBizService.sendMessage(user.getPhone(), SmsTemplateEnum.ORDER_SMS_THREE.getValue(),
								json.toJSONString(), null);
					} catch (Exception e) {
						logger.error("[orderPurchaseReminderToUser]订单" + orderSubscribeDto.getOrderCode() + days
								+ "天后加购提醒短信异常",
								e);
					}
				}
			}
		} catch (Exception e) {
			logger.error("[orderPurchaseReminderToUser]" + days + "天后加购提醒短信异常:", e);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + days + "天后加购提醒短信异常," + e.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * 还车提醒(每天10点)-用户
	 * 
	 * @return
	 */
	@Override
	public boolean orderReturnReminderToUser() {
		try {
			// 查询1天后订单到期且无续订的订阅订单
			LocalDate leaseExpire = LocalDate.now().plusDays(1L);
			List<OrderSubscribeDto> orderSubscribeDtos = orderSubscribeService.getNoneRenewable(leaseExpire,
					OrderSubscribeStatusEnum.TRADE_USE);
			if (orderSubscribeDtos == null || orderSubscribeDtos.isEmpty()) {
				logger.info("[orderReturnReminderToUser]1天后无到期未续订订阅订单");
				return true;
			}
			// 车型ids
			List<Integer> vehicleIds = new ArrayList<>();
			// 门店ids
			List<Integer> storeIds = new ArrayList<>();
			// 用户ids
			List<Integer> userIds = new ArrayList<>();
			for (OrderSubscribeDto orderSubscribeDto : orderSubscribeDtos) {
				storeIds.add(orderSubscribeDto.getPlaceStoreId());
				vehicleIds.add(orderSubscribeDto.getVehicleId());
				userIds.add(orderSubscribeDto.getUserId());
			}
			// 查询门店
			Map<Integer, StoreDto> storeMap = storeService.getStoreMapByIds(storeIds);
			// 查询车型信息
			Map<Integer, VehicleNameBizDto> vehicleMap = vehicleBizService.getCarByModelNameList(vehicleIds);
			// 查询用户
			Map<Integer, UserDto> userMap = userService.getUsers(userIds);

			for (OrderSubscribeDto orderSubscribeDto : orderSubscribeDtos) {
				try {
					Thread.sleep(500);
				} catch (Exception e) {
				}
				StoreDto store = storeMap.get(orderSubscribeDto.getPlaceStoreId());
				if (store == null || StringUtils.isBlank(store.getFullName())) {
					continue;
				}
				VehicleNameBizDto vehicleName = vehicleMap.get(orderSubscribeDto.getVehicleId());
				if (vehicleName == null || StringUtils.isBlank(vehicleName.getModelName())) {
					continue;
				}
				UserDto user = userMap.get(orderSubscribeDto.getUserId());
				if (user == null || StringUtils.isBlank(user.getPhone())) {
					continue;
				}
				JSONObject json = new JSONObject();
				// 商品名称
				String product = vehicleName.getSubBrandName() + " " + vehicleName.getSeriesName() + " "
						+ vehicleName.getModelName() + " " + orderSubscribeDto.getTransportTime() + "个月/"
						+ orderSubscribeDto.getBaseMileage() + "公里, " + orderSubscribeDto.getPackageMileage() + "公里";
				json.put("product", product);
				// 到期日
				json.put("date", DateUtil.formatDate(leaseExpire, "yyyy年MM月dd日"));
				// 门店
				json.put("store", store.getFullName());
				try {
					smsBizService.sendMessage(user.getPhone(), SmsTemplateEnum.ORDER_SMS_ONE.getValue(),
							json.toJSONString(), null);
				} catch (Exception e) {
					logger.error("[orderReturnReminderToUser]订单" + orderSubscribeDto.getOrderCode() + "还车提醒短信发送异常", e);
				}
			}
		} catch (Exception e) {
			logger.error("[orderReturnReminderToUser]还车提醒短信发送异常:", e);
			DingTalkUtil.exceptionSend(ACTIVE_EXPLAIN + "还车提醒短信发送异常," + e.getMessage());
			return false;
		}

		return true;
	}


	/**
	 * 生成Excel
	 * @param list
	 */
	private ByteArrayInputStream toExcel(List<OrderScheduleReminderBizDto> list){
		ByteArrayOutputStream baos = null;
		ByteArrayInputStream is = null;
		try {
			List<String> titles =new  ArrayList<>();
			titles.add(0, "订单号");
			titles.add(1, "还款期数");
			titles.add(2, "应还款金额");
			titles.add(3, "应还款日");
			titles.add(4, "状态");
			titles.add(5, "车辆数");
			titles.add(6, "经销商名称");
			titles.add(7, "负责人姓名");
			titles.add(8, "联系电话");
			titles.add(9, "地址");

			List<List<String>> params=new ArrayList<>();
			for (OrderScheduleReminderBizDto dto : list) {
				DealerDto dealerDto = dealerService.getDealerById(dto.getDealerId());
				DealerDetailDto dealerDetailDto = dealerDetailService.getDealerDetailById(dto.getDealerId());
				List<String> contents=new ArrayList<>();
				contents.add(0,dto.getOrderCode().toString());
				contents.add(1,dto.getPeriods()+"/"+dto.getTotalPeriods());
				contents.add(2,dto.getPayable().add(dto.getDeposit()).toString());
				if(null == dto.getPayableDate()){
					contents.add(3,"-");
				}else{
					contents.add(3,DateUtil.formatDate(dto.getPayableDate()));
				}
				contents.add(4,dto.getStatus().getName());
				contents.add(5,dto.getCarCount().toString());
				contents.add(6,dealerDto.getFullName());
				contents.add(7,dealerDetailDto.getResponsibleName());
				contents.add(8,dealerDetailDto.getResponsiblePhone());
				contents.add(9,dealerDetailDto.getAddress());

				params.add(contents);
			}
			XSSFWorkbook createXSSFWorkbook = PoiExcelUtils.createXSSFWorkbook(titles, params);
			baos = new ByteArrayOutputStream();
			createXSSFWorkbook.write(baos);
			baos.flush();
			is = new ByteArrayInputStream(baos.toByteArray());

		} catch (Exception e) {
			logger.error("违章无法查询的车辆发送邮件异常:", e);
		}finally {
			if(null!= baos) {
				try {
					baos.close();
				} catch (IOException e) {

				}
			}
		}
		return is;
	}


	/**
	 * 获取邮件人信息
	 * @return
	 */
	private List<String> getEmail(RiskEmailTypeEnum riskEmailTypeEnum){
		List<RiskEmailDto> riskList = riskEmailService.getByType(riskEmailTypeEnum.getValue(),RiskEmailReceiveTypeEnum.EMAIL_RECIPIENT.getValue());
		List<String> list=null;
		if(null != riskList && !riskList.isEmpty()) {
			list=new ArrayList<>();
			for (RiskEmailDto dto : riskList) {
				list.add(dto.getEmail());
			}
		}
		return list;
	}

	/**
	 * 订单用户逾期加入黑名单
	 * 
	 * @return
	 */
	@Override
	public boolean orderUserBlacklist() {
		LocalDate payableDate = LocalDate.now().minusDays(1L);
		// 查询需加入黑名单信息
		List<UserOverdueBlacklistBizDto> list = orderScheduleBizService.getUserOverdueBlacklist(payableDate);
		if (list == null || list.isEmpty()) {
			logger.info("[orderUserBlacklist]1天前无到逾期未还用户");
			return true;
		}
		for (UserOverdueBlacklistBizDto userOverdueBlacklistBizDto : list) {
			// 查询用户信息
			UserBizDto userDto = null;
			try {
				// 查询用户信息
				userDto = userBizService.getUser(userOverdueBlacklistBizDto.getUserId());
			} catch (Exception e) {
				logger.error("[orderUserBlacklist]查询用户信息异常：", e);
				continue;
			}
			// 加入黑名单
			blacklist(userDto, userOverdueBlacklistBizDto.getReason());
		}
		return true;
	}

	/**
	 * 加入黑名单
	 *
	 * @param userDto
	 * @param reason
	 */
	private void blacklist(UserBizDto userDto, String reason) {
		try {
			BlacklistCreateDto createDto = new BlacklistCreateDto();
			createDto.setName(userDto.getRealName());
			createDto.setIdNumber(userDto.getIdNumber());
			createDto.setPhone(userDto.getPhone());
			createDto.setReason(reason);
			createDto.setType(BlacklistTypeEnum.AUTOMATIC.getValue());
			createDto.setOperationTime(LocalDateTime.now());
			if (blacklistService.createBlacklist(createDto)) {
				// 修改用户信息
				userService.modifyIsBlack(userDto.getId(), true);
			} else {
				logger.error("加入黑名单失败");
			}
		} catch (BizException e) {
			Integer code = 105;
			if (!code.equals(e.getExceptionCode())) {
				logger.error("加入黑名单异常：", e);
			}
		} catch (Exception e) {
			logger.error("加入黑名单异常：", e);
		}
	}

}
